package com.openyelp.actions.front;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.openyelp.shiro.filter.UsernamePasswordCaptchaToken;
import com.openyelp.web.utils.FrontUtils;

/**
 * 登录controller
 * 
 * @author ty
 * @date 2015年1月14日
 */
@Controller
public class LoginController {

	/**
	 * 默认页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "loginxxx", method = RequestMethod.GET)
	public String loginxxx() {
		Subject subject = SecurityUtils.getSubject();
		if (subject.isAuthenticated() || subject.isRemembered()) {
			return "redirect:" + "login.htm";
		}
		return "login";
	}
	/**
	 * 登录失败
	 * @param userName
	 * @param model
	 * @return
	 */
	@RequestMapping(value="login",method = RequestMethod.POST)
	public String fail(@RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String userName, Model model) {
		model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, userName);
		return FrontUtils.getPath("login");
	}
	/**
	 * 登录失败
	 * 
	 * @param userName
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "login1x", method = RequestMethod.POST)
	public String fail(
			@RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String userName,
			String password, Model model) {
		model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM,
				userName);
		Subject subject = SecurityUtils.getSubject();
		if (!subject.isAuthenticated()) {
			UsernamePasswordCaptchaToken token = new UsernamePasswordCaptchaToken();
			token.setUsername(userName);
			token.setPassword(password.toCharArray());
			try {
				subject.login(token);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (subject.isAuthenticated()) {
				return "redirect:" + "/admin/index.htm";
			} else {
				return "login";
			}
		}
		return "login";
	}

	/**
	 * 登出
	 * 
	 * @param userName
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "logout")
	public String logout(Model model) {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return FrontUtils.getPath("login");
	}

}
